package com.jprocms.module.cms.inteceptor;

import com.jprocms.module.cms.dal.dataobject.site.SiteDO;
import com.jprocms.module.cms.enums.EnumIntCommonStatus;
import com.jprocms.module.cms.enums.ErrorCodePortalConstants;
import com.jprocms.module.cms.exception.PortalServiceExceptionUtil;
import com.jprocms.module.cms.util.CmsContextUtil;
import com.jprocms.module.cms.util.DeviceUtil;
import com.jprocms.module.cms.util.FrontContextUtil;
import com.jprocms.module.cms.util.RequestUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.jpro.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.jprocms.module.cms.constant.CmsSysConstants.FRONT_API;
import static com.jprocms.module.cms.enums.ErrorCodeConstants.SITE_CLOSED;
import static com.jprocms.module.cms.util.FrontContextUtil.RESOURCE;

/**
 * 前台拦截器
 * 主要作用于页面跳转设置model参数 不用于api接口
 *
 * @author jprocms
 */
@Slf4j
public class FrontContextInterceptor implements HandlerInterceptor {

    public FrontContextInterceptor() {
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        CmsContextUtil.setPc(DeviceUtil.isPc());
        SiteDO site = CmsContextUtil.getSite();
        if (EnumIntCommonStatus.CLOSE.getStatus().equals(site.getStatus())) {
            final String requestUrl = RequestUtils.getRequestUrl(request);
            //关闭页面不进入错误提示
            if (!requestUrl.startsWith("/error")) {
                log.error("站点已关闭,站点ID:{} 站点名称:{}", site.getId(), site.getName());
                //接口请求返回json异常
                if (requestUrl.startsWith(FRONT_API)) {
                    throw exception(SITE_CLOSED);
                } else {
                    throw PortalServiceExceptionUtil.exception(ErrorCodePortalConstants.SITE_CLOSE);
                }
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           @Nullable ModelAndView modelAndView) {
        SiteDO site = CmsContextUtil.getSite();
        if (site == null) {
            // 设置 resource 让错误页面可以正确访问css js资源
            request.setAttribute(RESOURCE, CmsContextUtil.isPc() ? site.getResPath() : site.getH5ResPath());
            return;
        }
        FrontContextUtil.setData(request);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                                @Nullable Exception ex) {
        CmsContextUtil.clearPc();
    }
}
